package cn.wqb.bpp.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.ClassPathResource;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class FastjsonUtils {

    public static JSONObject getJsonFromResources(String fileName) {
        try {
            ClassPathResource resource = new ClassPathResource(fileName);
            InputStream inputStream = resource.getInputStream();
            StringBuilder sb = new StringBuilder();
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            JSONObject jsonNode = JSONObject.parseObject(sb.toString());
            br.close();
            inputStream.close();
            return jsonNode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String objectToString(Object obj) {
        String json = JSONObject.toJSONString(obj);
        return json;
    }

    public static <T> T stringToClass(String json, Class<T> clazz) {
        T object = JSONObject.parseObject(json, clazz);
        return object;
    }

    public static JSONObject objectToJson(Object obj) {
        return stringToJson(objectToString(obj));
    }

    public static JSONObject stringToJson(String json) {
        return JSONObject.parseObject(json);
    }
}
